<template>
  <div class="menu-content index-verify">
    <div class="top">
      <p class="right-title" style="margin-bottom: 20px;">指标数据校验-异常清单</p>
      <div style="display: flex;justify-content: space-between;">
        <div>总指标数：{{totalIndiNum}} &nbsp;&nbsp;&nbsp;&nbsp;正确指标数：{{correctIndiNum}} &nbsp;&nbsp;&nbsp;&nbsp;异常指标数：<span
            style="color:  #DF3838;">{{errorIndiNum}}</span></div>
        <div style="text-align: right;">
          <w-select v-model="procValue" placeholder="请选择" @change="procChange">
            <w-option v-for="item in procOptions" :key="item.id" :label="item.name" :value="item.name">
            </w-option>
          </w-select>
          <!-- <w-select v-model="indexValue" placeholder="请选择" @change="indexChange">
            <w-option v-for="item in indexOptions" :key="item.id" :label="item.zbName" :value="item.zbName">
            </w-option>
          </w-select> -->
          <w-select v-model="indexValue" filterable placeholder="请选择" @change="indexChange" @blur="searchBlur">
            <w-option v-for="item in indexOptions" :key="item.id" :label="item.zbName" :value="item.zbName">
            </w-option>
          </w-select>
          <w-date-picker :picker-options="pickerOptions" format="yyyy 年 MM 月" value-format="yyyy-MM" v-model="dateValue"
            type="month" @change="dateChange"></w-date-picker>
          <w-button type="primary" @click="moreCheck">{{allCheckInfo}}</w-button>
        </div>
      </div>
    </div>
    <div class="table">
      <w-table :max-height="tableHeight" border ref="multiTable" :data="tableData" style="width: 100%"
        @selection-change="handleSelectionChange">
        <w-table-column type="selection" width="50">
        </w-table-column>
        <w-table-column prop="zbId" label="指标ID">
        </w-table-column>
        <w-table-column prop="zbName" label="指标名称">
        </w-table-column>
        <w-table-column prop="standardSourceName" label="标准">
        </w-table-column>
        <w-table-column prop="compareOperator" label="规则">
        </w-table-column>
        <w-table-column prop="realValue" label="实际值">
          <template slot-scope="scope">
            <div>{{ scope.row.realValue || scope.row.realValue=='0' ? scope.row.realValue : '/' }}</div>
            <!-- <div>{{ scope.row.realValue}}</div> -->
          </template>
        </w-table-column>
        <w-table-column prop="lowestValue" label="低值">
          <template slot-scope="scope">
            <div>{{ scope.row.lowestValue || scope.row.lowestValue=='0' ? scope.row.lowestValue : '/' }}</div>
          </template>
        </w-table-column>
        <w-table-column prop="highestValue" label="高值">
          <template slot-scope="scope">
            <div>{{ scope.row.highestValue || scope.row.highestValue=='0'? scope.row.highestValue : '/' }}</div>
          </template>
        </w-table-column>
        <w-table-column prop="isAbnormal" label="校验结果">
          <template slot-scope="scope">
            <div :style="{'color':scope.row.isAbnormal==0?'#DF3838':scope.row.isAbnormal==1?'#5DB730':'#000622'}">{{ scope.row.isAbnormal==0?'异常':scope.row.isAbnormal==1?'正常':'未校验' }}</div>
          </template>
        </w-table-column>
        <!-- <w-table-column prop="diff" label="差值">
          <template slot-scope="scope">
            <div :style="{'color':scope.row.isAbnormal==0?'#DF3838':scope.row.isAbnormal==1?'#5DB730':'#000622'}">{{ scope.row.diff || scope.row.diff=='0' ? scope.row.diff : '/' }}</div>
          </template>
        </w-table-column>
        <w-table-column prop="diffRate" label="差异率">
          <template slot-scope="scope">
            <div :style="{'color':scope.row.isAbnormal==0?'#DF3838':scope.row.isAbnormal==1?'#5DB730':'#000622'}">{{ scope.row.diffRate || scope.row.diffRate=='0' ? `${scope.row.diffRate*100}%` : '/' }}</div>
          </template>
        </w-table-column> -->
        <w-table-column prop="operator" label="操作" width="150">
          <template slot-scope="{row,$index}">
            <a title="详情" class="detail" @click="openDrawer(row)"><i class="w-icon-list"></i></a>
            <!-- <a title="校验" class="check"><i class="w-icon-list"></i></a> -->
            <w-button size="small" type="primary" @click="check(row,$index)">{{checkInfo[$index]}}</w-button>
          </template>
        </w-table-column>
      </w-table>
    </div>
    <w-drawer position="right" :visible.sync="visible" @onClose="handleClose">
      <div class="content-container bottom">
        <div class="left-table">
          <p class="right-title" style="margin-bottom: 20px;">数据处理步骤-环节口径调整</p>
          <w-table border max-height="350" :data="tableData1" @row-click="rowClick">
            <w-table-column prop="stepNo" label="步骤">
            </w-table-column>
            <w-table-column prop="sectionName" label="环节概述">
            </w-table-column>
            <w-table-column prop="handleTypeName" label="类型">
            </w-table-column>
            <w-table-column prop="conditionTypeName" label="条件">
            </w-table-column>
            <w-table-column prop="logicNo" label="序号">
            </w-table-column>
            <w-table-column prop="caliberNameMap" label="调整">
              <template slot-scope="{row,$index}">
                <!-- <span>{{row.caliberNameMap}}</span> -->
                <w-select v-model="row.caliberName" placeholder="请选择" @change="caliberChange($event,row)">
                  <w-option v-for="item in row.caliberNameMap" :key="item.id" :label="item.name" :value="item.name">
                  </w-option>
                </w-select>
              </template>
            </w-table-column>
            <!-- <w-table-column prop="operator" label="操作">
              <template slot-scope="{row,$index}">
                <a v-if="!row.add" class="reduce" @click="reduce1(row)"><i class="w-icon-delete"></i></a>
                <a v-if="row.add" class="add" @click="add1($index)"><i class="w-icon-plus"></i></a>
              </template>
            </w-table-column> -->
          </w-table>
          <div class="button-wrap">
            <w-button type="primary" @click="goSql">SQL预览</w-button>
          </div>
        </div>
        <hr style="margin: 20px 0;" />
        <div>
          <!-- <w-input v-model="sqlContext" type="textarea"></w-input> -->
          <div id="wangeditor">
            <div ref="editorElem" style="text-align:left;"></div>
          </div>
          <div style="text-align: right;margin-top: 30px;">
            <w-button size="large" type="primary" @click="submitSql">提交</w-button>
          </div>
        </div>
      </div>
    </w-drawer>
  </div>
</template>
<script>
  import E from "wangeditor";
  import {
    getCurrentMonth
  } from '@/utils/index.js'
  export default {
    components: {

    },
    data() {
      return {
        editor: null,
        editorContent: '',
        caliber: '',
        sqlContext: '',
        visible: false,
        dateValue: '',
        procOptions: [],
        procValue: '',
        procId: '',
        indexOptions: [],
        indexValue: '',
        zbId: '',
        selection: [],
        tableData: [],
        tableData1: [],
        caliberId: '',
        rowZbId: '',
        rowAdd: '',
        rowStepId: '',
        ids: '',
        checkInfo: [],
        allCheckInfo: '校验',
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now() - 8.64e6; //如果没有后面的-8.64e6就是不可以选择今天的
          }
        },
        isChange: false,
        tableHeight: document.documentElement.clientHeight - 250,
        totalIndiNum: '', //总指标数
        correctIndiNum: '', //正确指标数
        errorIndiNum: '', //异常指标数
        isSql: this.$route.query.isSql,
      };
    },
    mounted() {
      this.editor = new E(this.$refs.editorElem);
      // 编辑器的事件，每次改变会获取其html内容
      this.editor.customConfig.onchange = html => {
        this.editorContent = html;
        // console.log(this.editorContent)
      };
      this.editor.customConfig.menus = [
        // 菜单配置
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        'justify', // 对齐方式
        'code', // 插入代码
        'undo', // 撤销
        'redo' // 重复
      ];
      this.editor.create(); // 创建富文本实例
    },
    created() {
      this.getProcData()
      this.dateValue = getCurrentMonth()
      this.getTotal()
      // if(this.isSql){
      //   this.openDrawer({zbId:this.rowZbId,procId:this.procId,add:false})
      // }
    },
    methods: {
      getTotal() {
        this.$Http
          .post("etlIndiDataCheckThreshold/findTotal")
          .then(response => {
            if (response.data.response.code == "1") {
              let content = response.data.response.data
              this.totalIndiNum = content.totalIndiNum
              this.correctIndiNum = content.correctIndiNum
              this.errorIndiNum = content.errorIndiNum
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      //点击步骤每一行
      rowClick(row) {
        this.sqlContext = row.sqlContext
        this.editor.txt.html(row.sqlContext)
        this.rowStepId = row.id
      },
      //提交SQL
      submitSql() {
        // console.log('11',this.editor.txt.html())
        this.sqlContext = this.editor.txt.html()
        let param = {
          sqlContext: this.sqlContext,
          id: this.rowStepId
        }
        this.$Http
          .post("etlProdSecInfo/updateSql", param)
          .then(response => {
            if (response.data.response.code == "1") {
              this.$message.success('提交成功~')
              // this.getStep()
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      caliberChange(val, row) {
        row.caliberNameMap.map((item, index) => {
          if (item.name == val) {
            this.caliberId = item.id
            this.caliber = item.name
          }
        })
        this.getStep()
      },
      //多个校验
      moreCheck() {
        if (this.selection.length == 0) {
          this.$message.error('请至少勾选一个需要校验的指标~')
        } else {
          if (this.allCheckInfo.indexOf('中') == -1) {
            var arr = []
            var obj = {}
            this.allCheckInfo = '校验中...'
            this.selection.map((item, index) => {
              obj.zbId = item.zbId
              obj.procId = this.procId
              obj.startDate = this.dateValue + '-01 00:00:00'
              obj.endDate = this.dateValue + '-31 23:59:59'
              arr.push(obj)
              this.tableData.map((i, k) => {
                if (item.id == i.id) {
                  this.$set(this.checkInfo, k, '校验中...')
                }
              })
            })
            this.$Http
              .post("etlIndiDataCheckThreshold/checks", arr)
              .then(response => {
                this.allCheckInfo = '校验'
                this.selection.map((item, index) => {
                  this.tableData.map((i, k) => {
                    if (item.id == i.id) {
                      this.$set(this.checkInfo, k, '校验')
                    }
                  })
                })
                if (response.data.response.code == "1") {
                  this.$message.success('校验成功~')
                  this.getCheckData()
                } else {
                  if (response.data.response.msg) {
                    this.$message.error(response.data.response.msg)
                  }
                }
              })
              .catch(error => {
                console.log(error);
              });
          }
        }
      },
      //单个校验
      check(row, index) {
        if (this.checkInfo[index].indexOf('中') == -1) {
          this.$set(this.checkInfo, index, '校验中...')
          let param = {
            endDate: this.dateValue + '-31 23:59:59',
            procId: row.procId,
            startDate: this.dateValue + '-01 00:00:00',
            zbId: row.zbId,
            thresholdId: row.thresholdId
          }
          this.$Http
            .post("etlIndiDataCheckThreshold/check", param)
            .then(response => {
              this.$set(this.checkInfo, index, '校验')
              // this.checkInfo[index] = '校验'
              if (response.data.response.code == "1") {
                this.$message.success('校验成功~')
                this.getCheckData()
              } else {
                this.$message.error(response.data.response.msg)
              }
            })
            .catch(error => {
              console.log(error);
            });
        }
      },
      //跳转到SQL预览页面
      goSql() {
        this.$router.push({
          path: '/verifySql',
          query: {
            procId: this.procId,
            rowZbId: this.rowZbId,
            caliberId: this.caliberId,
            ids: this.ids
          }
        });
      },
      //打开侧边抽屉
      openDrawer(row) {
        this.visible = true
        this.rowZbId = row.zbId
        this.rowAdd = row.add
        this.procId = row.procId
        this.getStep()
        // this.getModelData()
        // this.getTypeData()
      },
      //关闭抽屉
      handleClose() {
        this.visible = false
      },
      //日期切换事件
      dateChange(val) {
        this.dateValue = val
      },
      //指标下拉框切换
      indexChange(val) {
        this.indexOptions.map((i, k) => {
          if (i.zbName == val) {
            this.zbId = i.zbId
          }
        })
        this.getCheckData()
      },
      searchBlur(val) {

      },
      //存储过程下拉框切换
      procChange(val) {
        this.procOptions.map((i, k) => {
          if (i.name == val) {
            this.procId = i.id
          }
        })
        // this.indexValue = ''
        // this.zbId = ''
        this.getIndexData()
      },
      //多选框选择事件
      handleSelectionChange(val) {
        this.selection = val
      },
      //获取存储数据
      getProcData() {
        let param = {
          id: ''
        }
        this.$Http
          .post("etlProdInfo/findtableListInfo", param)
          .then(response => {
            console.log('表格数据', response.data)
            if (response.data.response.code == "1") {
              let content = response.data.response.data;
              content.unshift({
                name: '全部',
                id: ''
              })
              this.procOptions = content
              if (content.length > 0) {
                this.procValue = content[0].name
                this.procId = content[0].id
              }
              this.getIndexData()
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      //获取指标数据
      getIndexData() {
        let param = {
          procId: this.procId
        }
        this.$Http
          .post("etlProdSecIndicInfo/findIndicatorInfo", param)
          .then(response => {
            console.log('指标表格数据', response.data)
            if (response.data.response.code == "1") {
              let content = response.data.response.data;
              content.unshift({
                id: '',
                zbId: "",
                zbName: "全部"
              })
              this.indexOptions = content ? content : []
              this.indexValue = content ? content[0].zbName : ''
              this.zbId = content ? content[0].zbId : ''
              this.getCheckData()
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      //获取数据校验清单表格
      getCheckData() {
        let param = {
          procId: this.procId,
          zbId: this.zbId
        }
        this.$Http
          .post("etlIndiDataCheckThreshold/findtableListInfo", param)
          .then(response => {
            // console.log('类型数据', response.data)
            if (response.data.response.code == "1") {
              let content = response.data.response.data;
              this.tableData = content
              this.tableData.map((item, index) => {
                this.checkInfo.push('校验')
              })
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      //获取步骤数据
      getStep() {
        if (!this.rowAdd) {
          let param = {
            procId: this.procId,
            zbId: this.rowZbId,
            id: this.caliberId
          }
          this.$Http
            .post("etlProdSecInfo/findSectionCaliberInfo", param)
            .then(response => {
              console.log('查询环节步骤', response.data)
              if (response.data.response.code == "1") {
                let content = response.data.response.data;
                this.tableData1 = content
                if (content.length > 0) {
                  this.sqlContext = content[0].sqlContext
                  this.editor.txt.html(content[0].sqlContext ? content[0].sqlContext : '')
                  this.rowStepId = content[0].id
                  this.caliber = content[0].caliberName
                  var arr = []
                  content.map((item, index) => {
                    arr.push(item.id)
                  })
                  this.ids = arr.join(',')
                } else {
                  this.editor.txt.html('')
                }
              } else {
                if (response.data.response.msg) {
                  this.$message.error(response.data.response.msg)
                }
              }
            })
            .catch(error => {
              console.log(error);
            });
        }
      },
    },
    destroyed() {}
  };
</script>

<style scoped lang="scss">
  .index-verify {
    padding: 10px;
    box-sizing: border-box;

    .date-picker-demo {
      width: 40%;
      display: inline-block;

      .w-date-editor {
        margin: 0 10px;
      }

      .range-separator {
        display: inline-block;
        line-height: 32px;
        vertical-align: middle;
        font-size: 14px;
      }
    }

    .right-value {
      width: 20%;
    }

    .table {
      margin-top: 20px;
    }

    .content-container {
      width: 945px;
      padding: 20px;
      box-sizing: border-box;
    }

    .button-wrap {
      margin-top: 20px;
      text-align: right;
    }
  }
</style>
